package GUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import logic.ChunkRepository;
import logic.Server;

public class GUI {

	public static JFrame frame;

	private Server server;
	public static void main(final String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Server server = new Server(args);
					
					@SuppressWarnings("unused")
					GUI window = new GUI(server);
					GUI.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 * @throws Exception 
	 */
	public GUI(Server server) throws Exception {
		this.server = server;
		initialize();
		 
		try
		{
			FileInputStream fileIn =new FileInputStream(Server.CHUNKS);
			ObjectInputStream in = new ObjectInputStream(fileIn);
			Server.setChunkRepository((ChunkRepository) in.readObject());
			in.close();

		}catch(IOException i)
		{
			
			long nSize;
			do{
			String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Size of Repository (in MB):",
                    "Size of Repository",
                    JOptionPane.PLAIN_MESSAGE,
                    null, null, 10);
			if(s==null)
				System.exit(0);
			try
			{
				if(s==null)
					System.exit(0);
			 nSize=Long.parseLong(s);
			}
			catch(Exception e)
			{
				nSize=-1;
			}
			}while(nSize<0);
			nSize=nSize*1024*1024;
			
			Server.setChunkRepository(new ChunkRepository(nSize));
		}
		//server.run();
		
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("Distributed Backup Service");
		frame.setBounds(100, 100,550, 500);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//MainPanel mainPanel = new MainPanel(server);
		frame.getContentPane().add(new StartPanel(server), BorderLayout.CENTER);
	}

}
